package com.chen.base.module.redis.utils;

import com.chen.base.module.redis.service.CacheService;
import com.chen.base.utils.SpringContextHolder;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author: ~龙~
 * @date: 2023/8/14 14:34
 **/
@Slf4j
@UtilityClass
public class ImageCodeUtil {

    /**
     * 图片验证码
     * @param cacheKey 缓存中的key
     * @param code code
     * @param response response
     */
    public void validateCode(String cacheKey,String code,HttpServletResponse response){
        createImageCode(response,code);
        CacheService cacheService = SpringContextHolder.getBean(CacheService.class);
        cacheService.set(cacheKey,code);
    }

    /**
     * 创建一张带有code的小图片，并写入到HttpServletResponse中
     * @param response response
     * @param code code
     */
    @SneakyThrows
    public void createImageCode(HttpServletResponse response,String code){
        BufferedImage image = new BufferedImage(80, 32, BufferedImage.TYPE_3BYTE_BGR);
        //获取绘图对象
        Graphics g = image.getGraphics();
        g.setColor(new Color(239, 239, 239));
        g.fillRect(0,0,80,32);
        //设置字体颜色
        g.setColor(new Color(49, 49, 49));
        //设置字体
        g.setFont(new Font("SimSong",Font.ITALIC,20));
        //字符串输出内容，水平起始坐标，垂直起始坐标。
        g.drawString(code, 14, 24);
        //画线条
        for (int i = 0; i < 20; i++) {
            g.setColor(new Color((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255)));
            g.drawLine((int) (Math.random()*50),(int) (Math.random()*30),(int) (Math.random()*80),(int) (Math.random()*80));
        }

        //输出图像
        ImageIO.write(image, "png",response.getOutputStream());
        g.dispose();
    }
}
